import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys


class Base():
    # 初始化驱动
    def __init__(self, driver):
        self.driver = driver

    # 打开浏览器
    def open_url(self, url):
        self.driver.get(url)

    # 时间 截屏的方法
    def time(self, name):
        t = time.strftime('%Y%m%d%H%M%S', time.localtime())
        self.driver.save_screenshot(t + name)

    # 封装定位元素的方法
    def find_element(self, loc):
        try:
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            print(f'元素定位不到{e}')
            # 调用封装截屏的方法
            self.time('error.png')

    # 封装点击的方案
    def click(self, loc):
        self.find_element(loc).click()

    # 封装输入的方法
    def send_keys(self, loc, info):
        self.find_element(loc).send_keys(info)

    # 封装悬浮的方法
    def move_to_element(self,loc):
        a = self.find_element(loc)
        ActionChains(self.driver).move_to_element(a).perform()

    # 封装鼠标双击事件
    def double_click(self,loc):
        a = self.find_element(loc)
        ActionChains(self.driver).double_click(a).perform()

    # 封装键盘回车事件
    def keys_Enter(self,loc):
        a = self.find_element(loc)
        a.send_keys(Keys.ENTER)

    # 封装窗口切换
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 封装浏览器事件 刷新浏览器
    def refresh(self):
        self.driver.refresh()

    # frame框架
    def in_frame(self,loc):
        self.driver.switch_to.frame(loc)